import router from './router/index.js';
// 存储的token的KEY
export const TOKEN_KEY = 'Authorization';

/**
 * 退出
 */
export function doLoginOut() {
	clearToken();
	toLogin(router.currentRoute.path);
}

/**
 * 跳转到登录
 * @param backUrl
 */
export function toLogin(backUrl = '') {
	router.push({
		name: 'Login',
		query: {
			backUrl
		}
	});
}

/**
 * 跳转到首页
 */
export function toHome() {
	try {
		const backUrl = router.currentRoute.query.backUrl;
		if (backUrl) {
			router.push({path: backUrl});
			return;
		}
		router.push({path: 'home'});
	} catch (ex) {
		router.push({path: '/'});
	}
}

/**
 * 获取 token
 * @returns {string}
 */
export function getToken() {
	// 你默认先给所有接口的请求头加上Authorization，因为后续会挂在4.2里，需要验证，目前测试的值用eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2ludHNreSIsImlhdCI6MTY5MzgwNjUwOTA1OSwiZXhwIjoxNjkzODEzNzA5MDU5LCJob3N0IjoiMTc1LjYuMTQzLjk4IiwiZ3Vlc3QiOiIxLjg1LjYuMTU2IiwidXNlciI6ImFwcGFkbWluIn0=.51C42BC9A5F995FC8AA15EEC12B79FD9C27B51DFE23FE44192E68E255ED8B2DA
	const token = localStorage.getItem(TOKEN_KEY);
	return token;
	// return isDev
	// 	? 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2ludHNreSIsImlhdCI6MTY5MzgwNjUwOTA1OSwiZXhwIjoxNjkzODEzNzA5MDU5LCJob3N0IjoiMTc1LjYuMTQzLjk4IiwiZ3Vlc3QiOiIxLjg1LjYuMTU2IiwidXNlciI6ImFwcGFkbWluIn0=.51C42BC9A5F995FC8AA15EEC12B79FD9C27B51DFE23FE44192E68E255ED8B2DA'
	// 	: getHashSearchParam('t__') || getQueryVariable('token') || ''
}

/**
 * 设置token
 * @param value
 */
export function setToken(value) {
	if (value) {
		localStorage.setItem(TOKEN_KEY, value);
	}
}

/**
 * 清除token
 */
export function clearToken() {
	localStorage.removeItem(TOKEN_KEY);
}

// 空值： [undefined, null, NaN, [], {}], 注意非空：0, false;
export function isEmpty(value) {
	switch (Object.prototype.toString.call(value)) {
	case '[object Undefined]':
		// eslint-disable-next-line no-void
		return value === void 0;
	case '[object Null]':
		return value === null;
	case '[object Number]':
		return isNaN(value);
	case '[object String]':
		return value === '';
	case '[object Boolean]':
		return false;
	case '[object Object]':
		return Object.keys(value).length === 0;
	case '[object Array]':
		return value.length === 0;
	default:
		return false;
	}
}

/**
 * 获取hash参数
 * @param key
 * @returns {string}
 */
export function getHashSearchParam(key) {
	const url = location.href;
	// 获取 hash 值，不包含 '#' 号
	const hash = url.substring(url.indexOf('#') + 1);
	// 查找 '?' 号所在的索引
	const searchIndex = hash.indexOf('?');
	// '?' 号后面接的是索引参数，如果找到则+1，去除'?' 号
	const search = searchIndex !== -1 ? hash.substring(searchIndex + 1) : '';
	// 把搜索参数字符串提过URLSearchParams转成对象形式
	const usp = new URLSearchParams(search);
	// 通过URLSearchParams自带的get方法，查询键所对应的值
	return usp.get(key);
}

/**
 * 获取URL参数
 * @param name
 * @returns {string|null}
 */
export function getQueryVariable(name) {
	const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
	const r = window.location.search.substr(1).match(reg); // search,查询？后面的参数，并匹配正则
	if (r !== null) return unescape(r[2]);
	return null;
}
